import { Frame } from '@/frame'
import UIBackPackModel from '../Model/UIBackPackModel'
import InputUtil from '@/InputUtil'
import ItemUtil from '@/ItemUtil'
import BaseUtil from '@/BaseUtil'
import SelectUtil from '@/SelectUtil'
import ObjectPool from '@/ObjectPool'
import { formatExtrItemInfo } from '../common'
import BuffUtil from '@/BuffUtil'
import FrameTipUtil from '../common/FrameTipUtil'
import SyncUtil from '@/SyncUtil'
import EquipmentQuality from 'code/Scripts/Items/EquipmentQuality'

export default class UIBackPackView {
    private uiPool: ObjectPool<Frame[]> = new ObjectPool(this.poolCreator)
    model: UIBackPackModel
    poolCreator() {
        let f = Frame.createFrame()
        let _this = UIManager.UIBakpack
        f.setSize(0.025, 0.025).setParent(_this.rootFrame.current)
        let bg = f.addBackgroundImage('assets\\backpack\\grid.blp')
        let text = Frame.createTEXT(f.current).setSize(0.023, 0.012)
        text.setText('')
            .setFont(0.01113, 'fonts\\fonts.ttf')
            .setPoint(
                FRAMEPOINT_BOTTOMRIGHT,
                f.current,
                FRAMEPOINT_BOTTOMRIGHT,
                -0.002,
                0.001
            )
            .setTextAlignment(TEXTALIGN_BOTTOMRIGHT)
        let but = Frame.createBUTTON(f.current)
            .setSize(0.025, 0.025)
            .setPoint(FRAMEPOINT_CENTER, f.current, FRAMEPOINT_CENTER)
        but.setOnMouseEnter(UIBackPackView.showTip)
        but.setOnMouseLeave(UIBackPackView.hideTip)
        but.setOnClick(UIBackPackView.bagGridLeftClickEvenHandle)
        return [f, bg, text, but]
    }
    /** 每个物品格子的点击事件处理 */
    static bagGridLeftClickEvenHandle() {
        let p = DzGetTriggerKeyPlayer()
        let h = DzGetTriggerUIEventFrame()
        let _this = UIManager.UIBakpack
        // 确保点击的是 背包格子
        if (!_this.isEventOnBagBut(h)) return
        let data = _this.frameMapTipData.get(h)
        if (!data) return
        // _this.model.removeItemByIndex(data.index, p);
        // 清除ui提示数据
        for (let [handle, info] of _this.frameMapTipData) {
            if (info.index == data.index) {
                _this.frameMapTipData.delete(handle)
                break
            }
        }
        SyncUtil.syncObjData('ADD_true_item', data)
    }
    /** 点击的是否是背包格子 */
    isEventOnBagBut(h: number) {
        let keys = this.frameMapTipData.keys()
        for (let key of keys) {
            if (key == h) {
                return true
            }
        }
        return false
    }
    /** UI提示数据存储 */
    frameMapTipData: Map<number, UIBackPackItemModel> = new Map()
    /** 显示物品提示 */
    static showTip(this: void) {
        let handle = DzGetTriggerUIEventFrame()
        let p = DzGetTriggerUIEventPlayer()
        if (p == GetLocalPlayer()) {
            let _this = UIManager.UIBakpack
            let data = _this.frameMapTipData.get(handle)
            if (data == null) return
            // let text = `${EXGetItemDataString(data.id, 4)}|n|n${EXGetItemDataString(data.id, 3)}` + AbilityIncreaseInstence.getItemIncreaseTip(null, data.attr);
            const nameText = EquipmentQuality.Util.getQualityNameByAttribute(
                data.name,
                data.attr
            )
            const desc = EquipmentQuality.Util.getQualityDescForBackPack(
                data.id,
                data.attr
            )
            let text =
                `${nameText}|n${desc}|n${EXGetItemDataString(data.id, 3)}` +
                AbilityIncreaseInstence.getItemIncreaseTip(null, data.attr)
            _this.tipFrame.setText(text)
            _this.tipFrame.visible = true
            _this.tipBackground.visible = true
        }
    }
    static hideTip(this: void) {
        UIManager.UIBakpack.tipFrame.setVisible(false)
        UIManager.UIBakpack.tipBackground.setVisible(false)
    }
    constructor() {
        this.model = new UIBackPackModel()
        // this.drawUI();
        // 物品栏右键双击处理
        InputUtil.onMouseRightButtonPressed(this.rightDoubleClickEventHandle)

        // 背包中物品右键单击物品处理
        DzTriggerRegisterMouseEventByCode(
            CreateTrigger(),
            2,
            0,
            false,
            this.bagGridRightClickEvenHandle
        )

        // 监听变化事件，刷新背包ui
        se.on('背包数据变化', this.refreshBackPackUI)
        // 当玩家选择英雄完毕之后画背包的ui
        se.on('created_hero', this.drawUI.bind(this))
    }
    bagGridRightClickEvenHandle(this: void) {
        let p = DzGetTriggerKeyPlayer()
        let h = DzGetMouseFocus()
        let playerId = GetPlayerId(p)
        let _this = UIManager.UIBakpack
        if (!_this.isEventOnBagBut(h)) return
        let d = _this.frameMapTipData.get(h)
        if (!d.canStack) return
        let hero = SelectUtil.getAnHero(playerId)
        if (BuffUtil.hasUnitBuff(hero, StunSystemIntance.buffId)) {
            FrameTipUtil.showFailText('该物品无法使用')
            return
        }
        let { id, count, index } = d
        // _this.model.useItem(d, p);
        SyncUtil.syncObjData('BACKPACK_USE_ITEM', { id, count, index })
    }
    /** 通过事件来刷新背包界面 */
    refreshBackPackUI(this: void, data: { p: player }) {
        if (data.p != GetLocalPlayer()) return
        UIManager.UIBakpack.showBackPackItem(data.p)
    }
    /** 显示指定玩家的背包物品 */
    showBackPackItem(p: player) {
        if (p != GetLocalPlayer()) return
        let _this = UIManager.UIBakpack
        _this.uiPool.setAllIdleStatus(true)
        let root = _this.rootFrame
        _this.frameMapTipData.clear()
        for (let i = 0; i < _this.model.backPackSize; i++) {
            let [f, bg, text, but] = _this.uiPool.borrowObject()
            let x = 0.005 + (i % 6) * 0.028
            let y = -0.06 + Math.floor(i / 6) * -0.028
            f.setPoint(
                FRAMEPOINT_TOPLEFT,
                root.current,
                FRAMEPOINT_TOPLEFT,
                x,
                y
            )
            let data = _this.model.DB[GetPlayerId(p)][i]
            if (data) {
                bg.setTexture(data.art)
                if (data.canStack) {
                    text.setText(data.count.toString())
                }
                _this.frameMapTipData.set(but.current, data)
            } else {
                bg.setTexture('assets\\backpack\\grid.blp')
                text.setText('')
            }
        }
        _this.uiPool.forDirtyObjects(_this.forDirtyObjects)
    }
    forDirtyObjects(f: any) {
        f[0].visible = false
    }
    lastId = -1
    lastItem: item = null
    /** 右键双击的处理 */
    rightDoubleClickEventHandle() {
        let x = InputUtil.getMouseSceneX()
        let y = InputUtil.getMouseSceneY()
        let slotIndex = ItemUtil.getItemSlotBySceneXY(x, y)
        if (!slotIndex) return
        let _this = UIManager.UIBakpack
        if (_this.lastId == -1) {
            _this.lastId = slotIndex
            BaseUtil.runLater(0.5, _this.resetOrderId)
        } else {
            if (_this.lastId == slotIndex) {
                let u = SelectUtil.getRealSelectUnit()
                let it = UnitItemInSlot(u, slotIndex)
                if (GetHandleId(it) == 0) return
                if (it == _this.lastItem) return
                _this.lastItem = it
                _this.model.addItem(it, GetOwningPlayer(u), u)
                BaseUtil.runLater(0.5, _this.resetItem)
            }
        }
    }
    resetItem(this: void) {
        UIManager.UIBakpack.lastItem = null
    }
    resetOrderId(this: void) {
        UIManager.UIBakpack.lastId = -1
    }
    xz
    rootFrame: Frame
    tipBackground: Frame
    tipFrame: Frame
    /** 绘制基本的UI */
    drawUI() {
        // 绘制ui
        let bg = Frame.createBackDrop()
        bg.setTexture('assets\\backpack\\bag.blp')
        bg.setSize(0.03, 0.03).setAbsPoint(FRAMEPOINT_BOTTOMLEFT, 0.045, 0.165)
        let openBut = Frame.createGLUETEXTBUTTON()
        openBut.setSize(0.03, 0.03).setPoint2Center(bg.current)
        openBut.setOnClick(this.toggleBackPack)

        let root = (this.rootFrame = Frame.createFrame())
        root.setSize(0.175, 0.22)
            .setAbsPoint(FRAMEPOINT_LEFT, 0.48, 0.4)
            .setVisible(false)
        let rbg = new Frame(
            'BACKDROP',
            null,
            root.current,
            '_sl_border_backdrop',
            0
        )
        // root.addBackgroundImage('assets\\backpack\\black.blp');
        rbg.setPoints(root.current, 0.008, 0.008)
        let closeBut = Frame.createGLUETEXTBUTTON(root.current)
        closeBut
            .setSize(0.015, 0.015)
            .setPoint(
                FRAMEPOINT_TOPRIGHT,
                root.current,
                FRAMEPOINT_TOPRIGHT,
                -0.005,
                -0.005
            )
            .addBackgroundImage('assets\\common\\but_close.blp')
        closeBut.setOnClick(this.toggleBackPack)
        let tip = Frame.createTEXT(root.current)
            .setSize(0.08, 0.012)
            .setText('背包')
            .setFont(0.01, 'fonts\\fonts.ttf')
        tip.setPoint(
            FRAMEPOINT_TOP,
            root.current,
            FRAMEPOINT_TOP,
            0,
            -0.005
        ).setTextAlignment(TEXTALIGN_CENTER)

        // 提示信息
        this.tipBackground = new Frame(
            'BACKDROP',
            null,
            null,
            '_sl_border_backdrop',
            0
        )
        this.tipFrame = Frame.createTEXT()
            .setFont(0.01113, 'fonts\\fonts.ttf')
            .setPoint(
                FRAMEPOINT_TOPRIGHT,
                root.current,
                FRAMEPOINT_TOPLEFT,
                -0.01,
                0
            )
            .setSize(0.14, 0)
        this.tipBackground.setPoints(this.tipFrame.current, 0.007, 0.007)
        this.tipFrame.setVisible(false)
        this.tipBackground.setVisible(false)

        let tipText = Frame.createTEXT(root.current)
        tipText
            .setText('左键取出物品，右键使用物品')
            .setSize(0.17, 0.012)
            .setPoint(
                FRAMEPOINT_BOTTOMLEFT,
                root.current,
                FRAMEPOINT_BOTTOMLEFT,
                0.005,
                0.005
            )
            .setFont(0.012, 'fonts\\fonts.ttf')

        // 背包内按钮
        let but1 = Frame.createGLUEBUTTON()
        but1.setParent(root.current)
            .setSize(0.04, 0.02)
            .setPoint(
                FRAMEPOINT_TOPLEFT,
                root.current,
                FRAMEPOINT_TOPLEFT,
                0.005,
                -0.03
            )
            .addBackgroundImage('assets\\common\\but_sort.blp')
        but1.setOnClick(this.sort)
        let but2 = Frame.createGLUEBUTTON()
        but2.setParent(root.current)
            .setSize(0.04, 0.02)
            .setPoint(
                FRAMEPOINT_TOPLEFT,
                root.current,
                FRAMEPOINT_TOPLEFT,
                0.05,
                -0.03
            )
            .addBackgroundImage('assets\\common\\but_com.blp')
        but2.setOnClick(this.recipes)
    }
    recipes() {
        let p = DzGetTriggerUIEventPlayer()
        let pid = GetPlayerId(p)
        let _this = UIManager.UIBakpack
        for (let [key, value] of RecipeSystemInstance.recipeList) {
            let can = true
            for (let id in value) {
                let c = value[id]
                let tc = _this.model.getItemCount(id, pid)
                if (tc < c) {
                    can = false
                }
            }
            if (can) {
                SyncUtil.syncObjData('BACKPACK_RECISE_ITEM', { key, value })
            }
        }
        // let db = BackPack.db[pid];
    }
    sort() {
        SyncUtil.syncData('backpack_sort_item')
    }
    /** 点击显示与隐藏背包ui */
    toggleBackPack() {
        let p = DzGetTriggerUIEventPlayer()
        let _this = UIManager.UIBakpack
        _this.rootFrame.visible = !_this.rootFrame.visible
        _this.rootFrame.visible && _this.showBackPackItem(p)
    }
}
